package com.mhd.usercontroller.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
@RestController
public class DownloadController {

    // 处理文件上传路径，使用依赖注入从propeties文件中获取配置
    @Value("${file.upload.path}")
    String fileUploadPath;

    @GetMapping("/download")
    public void download(String filename, HttpServletResponse response) throws IOException {

        log.debug("下载导出的文件:{}",filename);

        // 定位要下载的文件的绝对路径
        final String finalFilepath = fileUploadPath + filename;

        // 让浏览器以附件的形式下载文件
        response.setHeader("content-disposition","attachment;filename="+filename);

        // 把文件内容写入响应对象的输出流中
        IOUtils.copy(new FileInputStream(finalFilepath),response.getOutputStream());

    }
}
